﻿using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using ChuanYe.CountyFireManagement.Model;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class FireFieldBLL
    {
        #region 构造单例
        private FireFieldBLL() { }
        private static FireFieldBLL _instance;
        public static FireFieldBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new FireFieldBLL());
            }
        }
        #endregion
        public ResultDto<List<FireMQTTResponseModel>> Complete(int fireId, int sceneUserId, string sceneContent, List<Firefieldattach> firefieldattaches, DateTime? sceneTime,  string reviseLatitude, string reviseLongitude, string reviseAltitude, string ip)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();
            var fireInfo = BLL.FireInfoBLL.Instance.Get(fireId);
            if (fireInfo == null)
            {
                result.Status = -1;
                result.Message = "FireInfo Is Not Exist";
                return result;
            }

            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Firefield.Where(p => p.FireId == fireId && p.SceneUserId == sceneUserId && p.SceneTime.HasValue == false).FirstOrDefault();
                if (exist == null)
                {
                    result.Status = -2;
                    result.Message = "Firefield Is Not Exist";
                    return result;
                }
                exist.SceneTime = sceneTime ?? DateTime.Now;
                exist.FieldContent = sceneContent;
                exist.ReviseLatitude = reviseLatitude;
                exist.ReviseLongitude = reviseLongitude;
                exist.ReviseAltitude = reviseAltitude;
                ef.Firefield.Add(exist);
                ef.Entry<Firefield>(exist).State = EntityState.Modified;
                ef.SaveChanges();

                foreach (var item in firefieldattaches)
                {
                    item.FieldId = exist.FieldId;
                    ef.Firefieldattach.Add(item);
                    ef.Entry<Firefieldattach>(item).State = EntityState.Added;
                    ef.SaveChanges();
                }

                //外勤
                var userInfo = ef.Userinfo.Where(p => p.UserId == sceneUserId).FirstOrDefault();
                Record record = new Record();
                record.FireId = exist.FireId;
                record.HandleTime = DateTime.Now;
                record.Type = (int)RecordType.外勤核实;
                record.UserId = sceneUserId;
                record.Content = sceneContent;
                record.AddTime = record.HandleTime;
                record.Ip = ip;
                record.Applicant = userInfo.RealName;
                
                record.CustomData = exist.FieldId.ToString();
                ef.Record.Add(record);
                ef.Entry<Record>(record).State = EntityState.Added;


                //消息 外勤人员向排除人员回复完成消息
                Message message = new Message();
                message.FireId = fireInfo.FireId;
                message.Type = (int)MessageType.外勤调动;
                message.Content = exist.SceneContent;
                message.SendType = (int)MessageSendType.用户对用户发送;
                message.IsRead = 0;
                message.HandleTime = fireInfo.HappenDatetime;
                message.SendUserId = exist.SceneUserId;
                message.TargetUserId = exist.UserId;
                message.Ip = fireInfo.Ip;
                ef.Message.Add(message);
                ef.Entry<Message>(message).State = EntityState.Added;
                ef.SaveChanges();

                #region 装载消息
                List<Message> messages = new List<Message>() { message };
                result.FirstParam = MessageBLL.Instance.TransMessageToFireMQTTResponseModel(messages, record.Type.Value);
                #endregion
                ef.SaveChanges();
                return result;
            }
        }

        public ResultDto<List<FireMQTTResponseModel>> Add(Firefield firefield, Firesite firesite)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();
            var fireInfo = BLL.FireInfoBLL.Instance.Get(firefield.FireId);
            if (fireInfo == null)
            {
                result.Status = -1;
                result.Message = "FireInfo Is Not Exist";
                return result;
            }
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                firefield.RecordType = (int)RecordType.外勤调动;
                firefield.SendStatus = 0;
                ef.Firefield.Add(firefield);
                ef.Entry<Firefield>(firefield).State = EntityState.Added;
                ef.SaveChanges();

                var sceneUserInfo = ef.Userinfo.Where(p => p.UserId == firefield.SceneUserId).FirstOrDefault();
                var userInfo= ef.Userinfo.Where(p => p.UserId == firefield.UserId).FirstOrDefault();
                if (sceneUserInfo != null && userInfo!=null)
                {
                    if (firesite.FireId.HasValue && firesite.FireId.Value > 0
                         && !string.IsNullOrEmpty(firesite.Latitude) && !string.IsNullOrEmpty(firesite.Longitude))
                    {
                        //坐标地址转换
                        string[] longitudeSplit = firesite.Longitude.Split('|');
                        string longitudeString = longitudeSplit[0] + "度" + longitudeSplit[1] + "分" + longitudeSplit[2] + "秒";
                        string[] latitudeSplit = firesite.Latitude.Split('|');
                        string latitudeString = latitudeSplit[0] + "度" + latitudeSplit[1] + "分" + latitudeSplit[2] + "秒";
                        firesite.Content = $"外勤调动:预计经度:{longitudeString}，预计纬度:{latitudeString},预计海拔:{firesite.Altitude}";
                        firesite.RecordType= firefield.RecordType;
                        ef.Firesite.Add(firesite);
                        ef.Entry<Firesite>(firesite).State = EntityState.Added;
                        ef.SaveChanges();

                        Record siteRecord = new Record();
                        siteRecord.FireId = firefield.FireId;
                        siteRecord.HandleTime = firefield.TransDatetime;
                        siteRecord.Type = (int)RecordType.定位火点;
                        siteRecord.UserId = firefield.UserId;
                        siteRecord.Content = firesite.Content;
                        siteRecord.AddTime = firefield.TransDatetime;
                        siteRecord.Ip = firefield.Ip;
                        siteRecord.Applicant = sceneUserInfo.RealName;
                        siteRecord.CustomData = firesite.SiteId.ToString();
                        ef.Record.Add(siteRecord);
                        ef.Entry<Record>(siteRecord).State = EntityState.Added;
                        ef.SaveChanges();
                    }

                    var transDatetime = firefield.TransDatetime.ToString("yyyy年MM月dd日HH时mm分");
                    Record record = new Record();
                    record.FireId = firefield.FireId;
                    record.HandleTime = firefield.TransDatetime;
                    record.Type = (int)RecordType.外勤调动;
                    record.UserId = firefield.UserId;
                    record.Content = string.Format(FireInfoTool.GetFireInfoRecordFormat((int)record.Type), sceneUserInfo.RealName, sceneUserInfo.Phone);
                    record.AddTime = firefield.TransDatetime;
                    record.Ip = firefield.Ip;
                    record.Applicant = sceneUserInfo.RealName;
                    
                    record.CustomData = firefield.FieldId.ToString();
                    ef.Record.Add(record);
                    ef.Entry<Record>(record).State = EntityState.Added;

                    //消息
                    Message message = new Message();
                    message.FireId = fireInfo.FireId;
                    message.Type = (int)MessageType.外勤调动;
                    message.Content = string.Format(FireInfoTool.GetFireInfoMessageFormat(message.Type), fireInfo.FireName,userInfo.RealName, userInfo.Phone);
                    message.SendType = (int)MessageSendType.用户对用户发送;
                    message.IsRead = 0;
                    message.HandleTime = fireInfo.HappenDatetime;
                    message.SendUserId = fireInfo.UserId.Value;
                    message.TargetUserId = firefield.SceneUserId;
                    message.Ip = fireInfo.Ip;
                    ef.Message.Add(message);
                    ef.Entry<Message>(message).State = EntityState.Added;
                    ef.SaveChanges();

                    #region 装载消息
                    List<Message> messages = new List<Message>() { message };
                    result.FirstParam = MessageBLL.Instance.TransMessageToFireMQTTResponseModel(messages,record.Type.Value);
                    #endregion

                }
                ef.SaveChanges();
                return result;
            }
        }
    }
}
